<?php


namespace App\Models\CacheModel;


use App\Models\Api\BaseCache;
use \Exception;
use AstroTool\Cache\CacheManage;

class ZlCouponActiveGiveRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zl_coupon_active_give_record';

    protected $cacheModel = 'user.coupon_active_give_record';

    /**
     * 获取活动优惠券领取记录
     * @param int $uid
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function getGiveRecord(int $uid)
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->getDataAndSet(function () use ($uid)
        {
            return $this->getGiveRecordByDb($uid);
        });

        return $data;
    }

    /**
     * 获取活动优惠券领取记录
     * @param int $uid
     * @return array
     */
    private function getGiveRecordByDb(int $uid): array
    {
        try
        {
            $data = $this->where('uid', $uid)->column('create_time', 'ca_id');
        }
        catch (Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 领取历史缓存添加
     * @param int $uid
     * @param array $recordData
     * @throws \Exception
     */
    public function cacheAddRecord(int $uid, array $recordData)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->setCache($recordData);
    }

    /**
     * 活动领取优惠券数量自增
     * @param int $uid
     * @param int $activeId
     * @param int $inc
     * @throws \Exception
     */
    public function activeGiveNumInc(int $uid, int $activeId, int $inc = 1): void
    {
        $cachekey = $activeId . ':' . $uid;

        CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cachekey)->hashDataInc('num', $inc, function () use ($uid, $activeId)
        {
            return $this->where('uid', $uid)->where('ca_id', $activeId)->count();
        });
    }

    /**
     * 获取活动领取优惠券数量
     * @param int $uid
     * @param int $activeId
     * @return int
     * @throws Exception
     */
    public function getActiveGiveNum(int $uid, int $activeId): int
    {
        $cachekey = $activeId . ':' . $uid;
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cachekey)->getDataAndSet(function () use ($uid, $activeId)
        {
            $num = $this->where('uid', $uid)->where('ca_id', $activeId)->count();

            return ['num' => $num];
        }, ['num']);

        return is_array($data) ? (int)$data['num'] : (int)$data;
    }
}
